package org.example.embeddedmysqldemo

import com.wix.mysql.EmbeddedMysql
import com.wix.mysql.config.MysqldConfig
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.context.junit4.SpringRunner

import java.sql.Connection
import java.sql.DriverManager
import java.sql.ResultSet
import java.sql.Statement

import static com.wix.mysql.EmbeddedMysql.anEmbeddedMysql
import static com.wix.mysql.ScriptResolver.classPathScript
import static com.wix.mysql.ScriptResolver.classPathScripts
import static com.wix.mysql.config.Charset.UTF8
import static com.wix.mysql.config.MysqldConfig.aMysqldConfig
import static com.wix.mysql.distribution.Version.v5_7_latest
import static org.hamcrest.core.Is.is
import static org.junit.Assert.assertThat

@RunWith(SpringRunner)
@SpringBootTest
class EmbeddedMysqlDemoApplicationTests {

	private EmbeddedMysql mysqld

	@Before
	void mysqldConfigAndMultipleSchemas() {
		MysqldConfig config = aMysqldConfig(v5_7_latest)
				.withCharset(UTF8)
				.withPort(2215)
				.withUser("user", "password")
				.build()

		mysqld = anEmbeddedMysql(config)
				.addSchema("schema1", classPathScript("db/001_init.sql"))
				.addSchema("schema2", classPathScripts("db/*.sql"))
				.start()
	}

	@After
	void cleanup(){
		mysqld.stop() //optional, as there is a shutdown hook
	}

	@Test
	void ensureMysqlIsWorking() {
		def url = "jdbc:mysql://localhost:2215/schema1"
		final Connection conn = DriverManager.getConnection(url, "user", "password")
		final Statement statement = conn.createStatement()
		assertThat(statement.execute("SELECT * FROM t1;"), is(true))
		final ResultSet resultSet = statement.getResultSet()
		assertThat(resultSet.next(), is(true))
		assertThat(resultSet.getInt("col1"), is(10))
		assertThat(resultSet.getString("col2"), is("zzz"))
	}

}
